package com.analyse.stock.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.analyse.stock.constant.StockConstant;
import com.analyse.stock.enums.StrategyEnum;
import com.analyse.stock.form.PickStockQueryForm;
import com.analyse.stock.model.StockAnalyseFocusModel;
import com.analyse.stock.service.IStockAnalyseFocus;
import com.analyse.stock.strategy.StrategyHandle;
import com.analyse.stock.utils.PublicHolidayUtil;
import com.analyse.stock.utils.StockStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 每日实盘操作
 * 每日早上 9：30 开始执行
 */
@Component
@Slf4j
public class AutoTradingJob implements Job {

    @Autowired
    private StrategyHandle strategyHandle;

    @Autowired
    private IStockAnalyseFocus stockAnalyseFocus;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public void execute(JobExecutionContext context) {
        Date now = new Date();
        boolean isTrading = PublicHolidayUtil.isTradingDateTime("XSHE",now, StockStringUtil.tradingTimeFun);
        log.info("### 开始实时同步每日分时1min资金流向信息,当前时间：{} , 【{}】交易时间 ###",
                DateUtil.format(now, DatePattern.NORM_TIME_PATTERN),isTrading?"正在":"不在");
        if(!isTrading){
            return;
        }
        StockAnalyseFocusModel queryModel = StockAnalyseFocusModel.me(1,
                DateUtil.offsetDay(DateUtil.date(),-1), BigDecimal.valueOf(200), StrategyEnum.T1_TRADING_STRATEGY,BigDecimal.valueOf(80));
        List<StockAnalyseFocusModel> focusList = stockAnalyseFocus.getFocusList(queryModel);
        if(CollUtil.isEmpty(focusList)){
            log.info("### 在【股票池】中未发现需要关注的股票，今日不进行实盘操作....");
            return;
        }

        /**
         * 登录账户的  资金账户信息
         * 可用资金，自动交易可用资金
         **/
        //TODO
        StockConstant.FUND_ACCOUNT_MAP.put("",null);
        //一个股票开一个线程
        for(StockAnalyseFocusModel focusModel : focusList){
            PickStockQueryForm queryForm = new PickStockQueryForm();
            queryForm.setStockCode(focusModel.getStockCode());
            CompletableFuture.runAsync(() ->
                    strategyHandle.getStrategy(focusModel.getStrategyCode()).run(JSONObject.toJSONString(queryForm)),
                    threadPoolExecutor);
            try {
                //股票之间错开1.5秒
                Thread.sleep(1500);
            } catch (InterruptedException ex) {
                log.error("### error:{}",ex.getMessage(),ex);
            }
        }
    }
}
